package com.killer.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    /**
     * 不需要登录就能访问的uril
     */
    private static List<String> unneedLoginUrl;

    static {
        unneedLoginUrl=new ArrayList<String>();
        unneedLoginUrl.add("/user/login");
        unneedLoginUrl.add("/user/register");
        unneedLoginUrl.add("/user/isRegistered");
        unneedLoginUrl.add("/code/create");
        unneedLoginUrl.add("/code/validate");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取请求的路径
        String path=request.getPath().toString();
        //检查是否需要登录
        if (!checkNeedLogin(path)) {
            //不需要登录的话直接放行就好
            return chain.filter(exchange);
        }
        //打印请求地址
        System.out.println(request.getURI().toString());
        //获取cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie token = cookies.getFirst("token");
        if (token == null) {
            ServerHttpResponse response = exchange.getResponse();
            // 决绝访问，返回
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            DataBuffer wrap = response.bufferFactory().wrap("please login".getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    private boolean checkNeedLogin(String path) {
        for (String url : unneedLoginUrl) {
            if (path.startsWith(url)) {
                //只要一个符合就返回
                return false;
            }
        }
        return true;
    }


    @Override
    public int getOrder() {
        //该过滤器放在防暴刷过滤器后面
        return 10;
    }
}
